<template>
  <a-modal :visible="visible" :footer="null" centered :width="446" :closable="false" @cancel="onClose"
    :destroyOnClose="true" wrapClassName="login_modal" style="background: transparent" :bodyStyle="{
      overFlow: 'hidden',
      padding: 0,
      background: 'transparent',
    }">
    <!-- :style="{
      height: isForgetPwd
        ? '600px'
        : loginChangeData?.key === 'code'
          ? '670px'
          : '520px',
    }" -->
    <div class="modal-content">
      <!-- 切换登录方式按钮 -->
      <div class="switch-type" @click="changeLoginMode(loginTypeSwitchValue)"
        v-if="!isForgetPwd && loginChangeData.key != 'code'">
        <div class="relative flex items-center justify-center w-full h-full">
          <img class="switch-type-img" :style="imgIconStyle" :src="btnIcon" />
          <!-- <div class="w-full h-full mask" :style="maskStyle"></div> -->
        </div>
      </div>

      <a-row justify="center">
        <a-col :span="24" style="text-align: center">
          <img v-if="!isForgetPwd" :src="systemLogo" style="height: 35px" />
          <h1 v-if="isForgetPwd" style="height: 50px; text-align: center">
            找回密码
          </h1>
        </a-col>
      </a-row>

      <div style="min-height: 230px">
        <!-- 微信扫码一键登录 -->
        <template v-if="loginMode == 'scan' && !isForgetPwd">
          <div class="flex mt-20 justify-center align-center scan-header">
            <div class="header-title">请使用微信扫码登录</div>
          </div>
          <div class="flex justify-center align-center scan-header" style="margin: 18px 0 10px 0">
            <div class="header-qrdesc">
              新用户扫码后，关注公众号自动创建账号
            </div>
          </div>
          <div class="login-qr-code flex justify-center align-center">
            <div style="width: 180px; height: 180px; margin-top: 0">
              <a-spin :spinning="spinCodeing" style="
                  display: flex;
                  justify-content: center;
                  align-items: center;
                ">
                <img :src="loginQrCodeUrl" class="login-qrcode" v-if="loginQrCodeUrl" />
                <div class="code-safe" v-if="!code_readCheck && loginQrCodeUrl">
                  <div style="width: 85px; text-align: center">
                    请阅读并勾选下方的协议
                  </div>
                </div>
              </a-spin>
            </div>
          </div>
          <div class="flex justify-center align-center scan-header" style="margin: 30px 0 10px 0">
            <div class="header-qrdesc">微信扫一扫</div>
          </div>

          <div class="info" style="display: flex; justify-content: center">
            <a-checkbox v-model:checked="code_readCheck" style="white-space: nowrap;">
              注册登录即代表您已同意<span style="color: var(--ss-primary-color)" class="cursor-pointer" @click.prevent="
                toUserAgreement('user_agreement_url', user_agreement_url)
                ">《用户服务条款》</span>和<span style="color: var(--ss-primary-color)" class="cursor-pointer" @click.prevent="
                  toUserAgreement('privacy_agreement', privacy_agreement)
                  ">《隐私协议》</span>
            </a-checkbox>
          </div>
        </template>
        <!-- 账号登录 -->
        <template v-if="loginMode == 'code' && !isForgetPwd">
          <div class="flex justify-center align-center scan-header" style="margin: 25px 0 5px 0">
            <div class="header-title">
              <div v-if="loginChangeData.key == 'code'">账号注册</div>
              <div v-if="loginChangeData.key == 'Verificode'">
                {{ loginChangeData.text }}
              </div>
              <div v-if="
                loginChangeData.key !== 'code' &&
                loginChangeData.key !== 'Verificode'
              ">
                账号登录
              </div>
            </div>
          </div>
          <div style="padding-top: 20px">
            <div class="flex align-center phone-input-wrap">
              <a-input placeholder="请输入您的手机号码" size="large" v-model:value="phoneNumber" :max-length="11" autofocus
                ref="phoneInputRef" class="phone-input" />
            </div>

            <div class="flex align-center code-input-wrap" v-if="
              loginChangeData.key == 'code' ||
              loginChangeData.key == 'Verificode'
            " style="border: none">
              <a-input placeholder="请输入短信验证码" type="number" size="large" v-model:value="verifyCode" :max-length="4"
                class="code-input" />
              <a-button type="link" :disabled="!phoneChecked || timeCounting" @click="getCode()"
                style="font-size: 16px; padding: 0; margin-left: 20px">{{ timeCounting ? `重新获取${timeCount} 秒` : `获取验证码`
                }}
              </a-button>
            </div>
            <div v-if="
              loginChangeData.key !== 'code' &&
              loginChangeData.key !== 'Verificode'
            " class="flex align-center code-input-wrap">
              <a-input type="password" placeholder="请输入密码" :maxlength="20"  size="large" v-model:value="password" class="code-input" />
            </div>
            <div v-if="loginChangeData.key == 'code'" class="flex align-center phone-input-wrap">
              <a-input placeholder="请输入主体名称" size="large" v-model:value="team_name" :maxlength="12" autofocus
                ref="phoneInputRef" class="phone-input" />
            </div>
            <div v-if="loginChangeData.key == 'code'" class="flex align-center phone-input-wrap">
              <a-input type="password" placeholder="请输入密码" :maxlength="20" size="large" autocomplete="new-password"
                v-model:value="password" class="code-input" />
            </div>
            <passwordTips v-if="loginChangeData.key == 'code'" :password="password"></passwordTips>
            <a-button type="primary" v-if="loginChangeData.key !== 'Verificode'" style="
                width: 360px;
                height: 55px;
                border-radius: 10px;
                margin: 20px 0 15px 0;
                border: none;
                font-size: 20px;
              " :style="{
                border: submitDisabled
                  ? '1px solid var(--ss-primary-2)'
                  : '1px solid #d9d9d9',
              }" :disabled="submitDisabled" :loading="submitLoading" @click="submitLogin">
              <span v-if="loginChangeData.key == 'code'">注册</span>
              <span v-else> 登录</span>
            </a-button>

            <a-button v-if="loginChangeData.key == 'Verificode'" class="Verificode_btn" type="primary"
              :disabled="verifyCode.length == 0" :loading="submitLoading" @click="submitLogin">
              登录
            </a-button>
          </div>
        </template>
        <!-- 忘记密码 -->
        <template v-if="isForgetPwd">
          <div style="padding-top: 20px">
            <div class="flex align-center phone-input-wrap">
              <a-input placeholder="请输入您的手机号码" size="large" v-model:value="phoneNumber" :max-length="11" autofocus
                ref="phoneInputRef" class="phone-input" />
            </div>

            <div class="flex align-center code-input-wrap" style="border: none">
              <a-input placeholder="请输入短信验证码" size="large" v-model:value="verifyCode" :max-length="4"
                class="code-input" />
              <a-button type="link" :disabled="!phoneChecked || timeCounting" @click="getCode()"
                style="font-size: 16px; padding: 0; margin-left: 20px">{{ timeCounting ? `重新获取${timeCount} 秒` : `获取验证码`
                }}
              </a-button>
            </div>
            <div class="flex align-center code-input-wrap" style="border: none">
              <a-input type="password" placeholder="请输入密码" size="large" v-model:value="password"
                autocomplete="new-password" class="code-input" />
            </div>
            <div class="flex align-center code-input-wrap" style="border: none">
              <a-input type="password" :maxlength="20"  placeholder="请输入确认密码" size="large" v-model:value="repeatPassword"
                autocomplete="new-password" class="code-input" @change="onInputChange"
                :style="passwordConsistent ? '' : 'border: 1px solid red; filter: drop-shadow(0px 0px 2px red)'" />
            </div>
            <passwordTips :password="repeatPassword"></passwordTips>

            <!-- background: submitDisabled
                  ? 'linear-gradient(90deg, var(--ss-primary-color) 0%, var(--ss-primary-4) 100%)'
                  : '',
                border: submitDisabled
                  ? '1px solid var(--ss-primary-2)'
                  : '1px solid #d9d9d9', -->
            <a-button type="primary" style="
                width: 360px;
                height: 55px;
                border-radius: 10px;
                margin: 20px 0 15px 0;
                border: none;
                font-size: 20px;
              " :disabled="submitDisabled" :loading="submitLoading" @click="handleChangePassword">
              确定
            </a-button>
          </div>
        </template>
      </div>

      <a-row>
        <a-col :span="24" class="flex justify-between align-center" style="display: flex">
          <div class="login_type" v-if="loginMode === 'code' || isForgetPwd">
            <!-- <div
              style="padding: 0"
              @click="
                () => changeLoginMode(loginMode === 'code' ? 'scan' : 'code')
              "
            >
              <cu-icon style="font-size: 20px" type="icon-weixin" />
            </div> -->
            <template v-if="loginChangeData.key === 'pwd' && !isForgetPwd && single_org_user">
              <div @click="LoginChange('code')">快速注册</div>
            </template>
            <template v-if="
              loginChangeData.key === 'code' ||
              isForgetPwd ||
              loginChangeData.key === 'Verificode'
            ">
              <div @click="LoginChange('pwd')">
                <a-space>
                  <cu-icon style="color: var(--ss-primary-color)" type="icon-shoujihao" />
                  账号登录
                </a-space>
              </div>
            </template>
          </div>

          <div style="display: flex">
            <a-button v-if="
              !isForgetPwd &&
              loginMode === 'code' &&
              loginChangeData?.key === 'pwd'
            " type="link" @click="LoginChange('Verificode')">验证码登录</a-button>

            <a-button v-if="
              !isForgetPwd &&
              loginMode === 'code' &&
              loginChangeData?.key === 'pwd'
            " type="link" @click="handleChangeResetPwd">忘记密码</a-button>
          </div>
        </a-col>
      </a-row>

      <div v-if="loginMode != 'scan' && !isForgetPwd">
        <a-col>
          <div class="info">
            <a-checkbox v-model:checked="readCheck" style="white-space: nowrap;">
              注册登录即代表您已同意<span style="color: var(--ss-primary-color)" class="cursor-pointer" @click.prevent="
                toUserAgreement('user_agreement_url', user_agreement_url)
                ">《用户服务条款》</span>和<span style="color: var(--ss-primary-color)" class="cursor-pointer" @click.prevent="
                  toUserAgreement('privacy_agreement', privacy_agreement)
                  ">《隐私协议》</span>
            </a-checkbox>
          </div>
        </a-col>
      </div>
    </div>
    <!-- 腾讯验证码弹层 -->
    <div id="captchaModal" v-show="showCaptcha">
      <iframe id="TestIframe" :src="captchaUrl" style="width: 100%; height: 100%" frameborder="no" border="0"
        marginwidth="0" marginheight="0" scrolling="no" allowtransparency="yes"></iframe>
    </div>

    <!-- 图形验证码弹层 -->
    <div class="imageVerify-modal-wrap" v-if="showImageVerify">
      <div class="imageVerify-modal">
        <CloseOutlined class="imageVerify-modal-close" @click="closeImageVerify" />
        <div class="flex align-center imageVerify-input-wrap">
          <div style="padding-right: 10px">图形验证码</div>
          <a-input placeholder="请输入图形验证码" size="large" v-model:value="imageVerifyCode" :max-length="4" autofocus
            ref="imageVerifyInputRef" class="imageVerify-input" />
          <img :src="imageVerifyImg" alt="" class="imageVerify-img" @click="getVerifyImage" />
          <SyncOutlined class="imageVerify-img-refresh" @click="getVerifyImage" />
        </div>
        <a-button class="imageVerify-btn" type="primary" size="large" @click="getSmsCode()"
          :disabled="!imageVerifyCode || imageVerifyCode.length < 4">
          确定
        </a-button>
      </div>
    </div>
    <!-- 用户服务条款弹窗 -->
    <a-modal :visible="userTextVisible" :title="agreementTitle" centered :width="800" :closable="false"
      :maskClosable="false" :bodyStyle="{
        overFlow: 'hidden',
        padding: 0,
      }">
      <div class="rich-text-wrapper" v-html="currentAgreeMentUrl"></div>
      <template #footer>
        <a-button @click="userTextClose" type="primary">我已知晓</a-button>
      </template>
    </a-modal>
    <!-- <Agreement ref="agreement" /> -->
  </a-modal>
</template>

<!-- <script src="https://turing.captcha.qcloud.com/TCaptcha.js"></script> -->

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  ref,
  nextTick,
  onMounted,
  createVNode
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Modal, notification, message } from "ant-design-vue";
import {
  WechatOutlined,
  CloseOutlined,
  SyncOutlined,
  ExclamationCircleOutlined 
} from "@ant-design/icons-vue";

import passwordTips from './component/passwordTips.vue'
import { debounce } from "lodash";
let qrCodeTimer = null;
export default defineComponent({
  name: "LoginModal",
  components: { WechatOutlined, CloseOutlined, SyncOutlined, passwordTips },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    zhuce: {
      type: Boolean,
      default: false,
    },
  },

  setup(props, context) {
    const route = useRoute();
    const router = useRouter();
    const state = reactive({
      userTextVisible: false,
      loginQrCodeUrl: "",
      loginMode: "code", //登录模式：code:手机验证码；scan:扫码
      spinCodeing: false,
      phoneNumber: "", //手机号
      verifyCode: "", //验证码
      team_name: "", // 团队名称
      password: "", //密码
      repeatPassword: "",
      phoneChecked: false, //获取手机验证码按钮可点击状态
      readCheck: false, // 是否勾选用户服务条款和隐私政策
      code_readCheck: false,
      timeCount: 60, // 重新获取验证码倒计时
      timeCounting: false, // 验证码是否在倒计时
      currentLoginType: "code",
      showCaptcha: false, // 是否展示腾讯码弹层
      captchaInfo: {}, // 腾讯验证码信息
      captchaUrl: "", // 腾讯验证码iframe地址

      submitDisabled: false,
      VerifiDisabled: true,
      submitLoading: false,
      user_agreement_url: "", //用户服务条款url
      privacy_agreement: "", //隐私协议url
      showImageVerify: false, // 是否展示图形码弹层
      imageVerifyToken: "", // 图形验证码-token
      imageVerifyCode: null, // 图形验证码-图片
      imageVerifyImg: "", // 图形验证码-输入
      single_org_user: false,
      // 忘记密码
      isForgetPwd: false,

      // loginChangeData: {
      //   text: "密码登录",
      //   key: "pwd",
      // },
      loginChangeData: {
        text: "验证码登录",
        key: "Verificode",
      },
      currentAgreeMentUrl: "", //打开协议弹窗链接
      agreementTitle: "", //打开协议弹窗标题
      remember_me: 0,


      passwordConsistent: true
    });

    const phoneInputRef = ref(null);
    const systemLogo = computed(
      () => store.getters.configInfo?.basic?.system_logo
    );

    const onClose = () => {
      context.emit("onClose");
    };

    const getQrCode = () => {

      let BASE_URL =  import.meta.env.ELECTRON ? import.meta.env.VITE_SITE_URL : request.BASE_URL;
      
      let params = {
        link: BASE_URL + "/h5/pages/chatAi/login?org_id=" + utils.getOrgId(),
        hideErrMsg: true,
      };
      let source = localStorage.getItem("USER_ACCESS_SOURCE");
      let sourceInfo = localStorage.getItem("USER_ACCESS_SOURCE_INFO");
      if (source) {
        params.link =
          BASE_URL +
          "/h5/pages/chatAi/login?org_id=" +
          utils.getOrgId() +
          "&source=" +
          source;
      }

      state.spinCodeing = true;
      request
        .get("/third", "/wechat/loginCode", { ...params })
        .then((res) => {
          state.loginQrCodeUrl = res.url;
          state.spinCodeing = false;

          state.loginMode = "scan";
          qrCodeTimer = setInterval(() => {
            // 检查登录
            request
              .get("/third", "/pc/checkLogin", { scene_id: res.scene_id })
              .then((result) => {
                if (typeof result == "object" && result.third_token) {
                  // 登录成功
                  clearInterval(qrCodeTimer);
                  qrCodeTimer = null;

                  request
                    .post("/user", "/login/afterThird", {
                      third_token: result.third_token,
                    })
                    .then((loginResult) => {
                      utils.setUserToken(loginResult.token).then(() => {
                        //获取智媒通的登录身份
                        let params = {
                          third_id: result.third_id,
                        };
                        let code =
                          localStorage.getItem("INVITE_CODE") ||
                          localStorage.getItem("teamInviteCode");
                        if (code) {
                          params.code = code;
                          localStorage.removeItem("INVITE_CODE");
                          localStorage.removeItem("teamInviteCode");
                        }
                        if (source) {
                          params.source = source;
                        }
                        if (sourceInfo) {
                          params.source_info = JSON.parse(sourceInfo);
                        }
                        request
                          .post("/work_ai", "/user/info", {
                            ...params,
                          })
                          .then((userResult) => {
                            store.commit(
                              "SET_TOKEN",
                              userResult.user.user_token
                            );
                            // 存userInfo
                            store.commit("SET_USER_INFO", userResult.user);

                            context.emit("loginCallback");
                          });
                      });
                    });
                }
              });
          }, 2000);
        })
        .catch((err) => {
          // 获取扫码错误时自动切换到验证码登录
          state.loginMode = "code";
          // 手机号码input自动聚焦
          nextTick(() => {
            if (phoneInputRef.value) {
              phoneInputRef.value.focus();
            }
          });
        });
    };

    const changeLoginMode = (mode) => {
      state.loginMode = mode;
      if (mode == "code") {
        state.loginChangeData.key = "pwd";
        clearInterval(qrCodeTimer);
        qrCodeTimer = null;
        // 手机号码input自动聚焦
        nextTick(() => {
          if (phoneInputRef.value) {
            phoneInputRef.value.focus();
          }
        });
      } else if (mode == "scan") {
        state.loginChangeData.key = "scan";
        getQrCode();
      }
    };

    const phoneFormat = (val, preVal) => {
      if (val && val.length > 11) {
        state.phoneNumber = preVal;
        return;
      }
      const reg = /^[0-9]*$/;
      if (reg.test(val)) {
        state.phoneNumber = val;
      } else {
        state.phoneNumber = preVal;
      }
    };

    /**************************************
     * @description: 手机号验证
     **************************************/
    // 监听电话号码输入
    watch(
      () => state.phoneNumber,
      (phone, prePhone) => {
        phoneFormat(phone, prePhone);
        if (phone.length == 11) {
          // 验证电话号码是否填写正确
          if (utils.phoneReg.test(phone)) {
            state.phoneChecked = true;
          } else {
            message.error("请输入正确的手机号码！");
          }
        } else if (phone.length < 11) {
          state.phoneChecked = false;
        } else if (phone.length < 11 && !state.phoneChecked) {
          state.phoneChecked = false;
        }
      }
    );

    /**************************************
     * @description: 获取验证码
     **************************************/
    const debouncedGetCode = debounce(() => {
      if(!state.readCheck){
        Modal.confirm({
          title: '提示',
          icon: createVNode(ExclamationCircleOutlined),
          content:'请确认已阅读并同意《服务协议》?',
          okText: '确认',
          cancelText: '取消',
          onOk() {
            state.readCheck = true
            state.timeCounting = true;
            state.timeCount = 60;
            store.dispatch("GetConfigInfo", true).then((config) => {
              if (config && config.captcha) {
                const { captcha_type, captcha_qcloud_appid } = config.captcha;
                if (captcha_type == 1) {
                  // 显示腾讯验证码 
                  let baseUrl = process.env.NODE_ENV === "production"
                    ? import.meta.env.VITE_SITE_URL
                    : "http://127.0.0.1";
                  state.captchaUrl = `${baseUrl}/public_web/qcloudCaptcha.html?qcloudAppid=${captcha_qcloud_appid}&t=${Math.random()}`;
                  state.captchaInfo = {};
                  state.showCaptcha = true;
                  codeTimer = setInterval(() => {
                      state.timeCounting = true;
                      if (state.timeCount == 0) {
                        clearTimer();
                        state.timeCounting = false;
                        state.timeCount = 0;
                        return
                      }
                      state.timeCount--;
                  }, 1000);
                } else if (captcha_type == 2) {
                  // 图形验证码
                  getVerifyImage();
                } else {
                  // 无需验证则进入短信验证码
                  getSmsCode();
                }
              } else {
                // 无需验证则进入短信验证码
                getSmsCode();
              }
            });
          },
        });
      }else{
        state.timeCounting = true;
        state.timeCount = 60;
        store.dispatch("GetConfigInfo", true).then((config) => {
          if (config && config.captcha) {
            const { captcha_type, captcha_qcloud_appid } = config.captcha;
            if (captcha_type == 1) {
              // 显示腾讯验证码 
              let baseUrl = process.env.NODE_ENV === "production"
                ? import.meta.env.VITE_SITE_URL
                : "http://127.0.0.1";
              state.captchaUrl = `${baseUrl}/public_web/qcloudCaptcha.html?qcloudAppid=${captcha_qcloud_appid}&t=${Math.random()}`;
              state.captchaInfo = {};
              state.showCaptcha = true;
              codeTimer = setInterval(() => {
                  state.timeCounting = true;
                  if (state.timeCount == 0) {
                    clearTimer();
                    state.timeCounting = false;
                    state.timeCount = 0;
                    return
                  }
                  state.timeCount--;
              }, 1000);
            } else if (captcha_type == 2) {
              // 图形验证码
              getVerifyImage();
            } else {
              // 无需验证则进入短信验证码
              getSmsCode();
            }
          } else {
            // 无需验证则进入短信验证码
            getSmsCode();
          }
        });
      }
    }, 1000); // 设置延迟时间，例如500毫秒

    // 使用防抖后的函数
    const getCode = () => {
      debouncedGetCode();
    };

    let codeTimer = null;
    const getSmsCode = () => {
      const params = {
        phoneCountry: "86",
        phone: state.phoneNumber,
        smsType: "sms_code",
        remark: `org_user_${state.currentLoginType}_login`,
        sms_code_length: 4,
      };
      store.dispatch("GetConfigInfo").then((config) => {
        if (config && config.captcha) {
          const { captcha_type } = config.captcha;
          if (captcha_type == 1) {
            params.captchaTicket = state.captchaInfo.ticket;
            params.captchaRandstr = state.captchaInfo.randstr;
          }
          if (captcha_type == 2) {
            params.captchaToken = state.imageVerifyToken;
            params.captchaInput = state.imageVerifyCode;
          }
          if (config.basic && config.basic.oem_org_id) {
            params.org_id = config.basic.oem_org_id;
          }
          request
            .post("/message", "/sms/sendSmsCodeGuest", params)
            .then(() => {
              message.success("验证码已发送");
              state.timeCount = 60;
              if (captcha_type == 2) {
                state.showImageVerify = false;
                state.imageVerifyCode = null;
                state.imageVerifyImg = "";
                state.imageVerifyToken = "";
              }
              codeTimer && clearTimer();
              codeTimer = setInterval(() => {
                state.timeCounting = true;
                if (state.timeCount == 0) {
                  clearTimer();
                  state.timeCounting = false;
                  state.timeCount = 0;
                  return
                }
                state.timeCount--;
              }, 1000);
            })
            .catch((err) => {
              // message.error("");
              state.timeCounting = false
              state.imageVerifyCode = null;
              clearTimer()
              // getVerifyImage();
            });
        }
      });
    };

    const clearTimer = () => {
      if (codeTimer) {
        state.timeCounting = false;
        clearInterval(codeTimer);
        codeTimer = null;
      }
    };

    const getAiConfig = () => {
      request.get("/work_ai", "/config").then((res) => {
        if (res.list) {
          console.log(res.list.user_agreement_url,'res.list.user_agreement_url');
          state.user_agreement_url = res.list.user_agreement_url;
          state.privacy_agreement = res.list.privacy_agreement;
          if (!res.list.single_org_user) {
            state.single_org_user = true
          }
        }
      });
    };

    function debounceFn(func, wait) {
      let timeout = null;
      return function () {
        let context = this,
          args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(function () {
          func.apply(context, args);
        }, wait);
      };
    }

    const handleMessage = (e) => {
      if (e.data) {
        const { type } = e.data;
        if (type === "qcloudCaptchaResult") {
          state.showCaptcha = false;
          const { res } = e.data;
          if (res && res.ticket && res.randstr && res?.ret === 0) {
            state.captchaInfo = res;
            getSmsCode();
          }
        }
      }
    };

    let myHandleMessage = debounceFn(function (event) {
      handleMessage(event);
    }, 200);

    const init = () => {
      let org_id = utils.getOrgId();
      if (org_id > 0) {
        getAiConfig();
      }
      //  监听腾讯验证码message
      window.addEventListener(
        "message",
        (e) => {
          if (e.data) {
            const { type } = e.data;
            if (type === "qcloudCaptchaResult") {
              state.showCaptcha = false;
              const { res } = e.data;
              if (res && res.ticket && res.randstr) {
                state.captchaInfo = res;
                getSmsCode();
              }
            }
          }
        },
        false
      );

      // 手机号码input自动聚焦
      nextTick(() => {
        if (phoneInputRef.value) {
          phoneInputRef.value.focus();
        }
      });

      state.remember_me = localStorage.getItem("remember_me");
      if (state.remember_me) {
        state.readCheck = true;
      }
    };

    watch(
      () => state.readCheck,
      (val) => {
        if (val) {
          state.remember_me = 1;
        } else {
          state.remember_me = 0;
        }
        localStorage.setItem("remember_me", state.remember_me);
      }
    );

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          // window.removeEventListener("message", myHandleMessage);
          clearInterval(qrCodeTimer);
          qrCodeTimer = null;
          state.showImageVerify = false;
          state.imageVerifyCode = null;
          state.imageVerifyImg = "";
          state.imageVerifyToken = "";
          state.loginChangeData = {
            text: "密码登录",
            key: "pwd",
          };
          state.phoneNumber = "";
          state.verifyCode = "";
          state.password = "";
          state.team_name = "";

          clearInterval(codeTimer);
          codeTimer = null;
          state.timeCounting = false;
          state.timeCount = 60;
        }
      }
    );

    // 监听验证码输入
    watch(
      () => [state.verifyCode, state.password],
      (code) => {
        if (state.loginChangeData.key == "code") {
          if (code[0].length == 4) {
            state.submitDisabled = false;
          } else {
            state.submitDisabled = true;
          }
        } else {
          if (code[1].length) {
            state.submitDisabled = false;
          } else {
            state.submitDisabled = true;
          }
        }
      },
      {
        immediate: true,
      }
    );

    const handleChangeResetPwd = () => {
      state.password = "";
      state.code = "";
      state.verifyCode = "";
      state.team_name = "";
      state.repeatPassword = "";
      state.isForgetPwd = true;
    };

    const submitLogin = () => {
      // debugger
      if (!state.readCheck) {
        message.warning("请确认已阅读并同意《服务协议》！");
        return;
      }

      // 注册的时候 才会校验密码
      if (state.loginChangeData?.key == "code") {
        const containsSpace = new RegExp("\\s");
        if (containsSpace.test(state.password)) {
          message.warning("密码不能包含空格");
          return
        }
      }


      state.submitLoading = true;
      let params = {
        phone_country: "86",
        phone: state.phoneNumber,
        code: state.verifyCode,
      };

      if (state.loginChangeData.key == "pwd") {

        params.password = state.password;
        params.code = undefined;
        // debugger
        request
          .post("/user", "/login/pwd", { ...params })
          .then((res) => {
            if (res.code == 1001) {
              state.submitLoading = false;
            }
            if (res.token) {
              setUserToken(res.token);
            }
          })
          .catch((err) => {
            state.submitLoading = false;
          });
        return;
      }

      if (state.loginChangeData?.key == "code") {
        params.password = state.password;
      }


      if (!state.verifyCode) return message.warning("请输入验证码");


      request
        .post("/user", "/login/reg", { ...params })
        .then((res) => {
          if (res.code == 1001) {
            state.submitLoading = false;
          }
          if (res.token) {
            setUserToken(res.token);
          }

        })
        .catch((err) => {
          state.submitLoading = false;
        });
    };

    let timer = null
    const onInputChange = () => {
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
      timer = setTimeout(() => {
        if (state.password !== state.repeatPassword) {
          state.passwordConsistent = false
          message.warning("两次密码不一致");
        } else {
          state.passwordConsistent = true
        }
      }, 500)


    }

    // 修改密码
    const handleChangePassword = () => {
      if (!state.verifyCode) return message.warning("请输入验证码");

      const containsSpace = new RegExp("\\s");
      if (containsSpace.test(state.password)) {
        message.warning("密码不能包含空格");
        return
      }
      // if (state.password.length < 6) {
      //   message.warning("密码不能少于6位");
      //   return
      // }

      state.submitLoading = true;
      let params = {
        phone_country: "86",
        phone: state.phoneNumber,
        code: state.verifyCode,
        password: state.password,
      };

      if (state.password !== state.repeatPassword) {
        message.warning("两次密码不一致");
        state.submitLoading = false;
        return;
      }

      request
        .put("user", "/changePassword", params)
        .then((res) => {
          if (res?.code && res.code != 1000) {
            state.submitLoading = false;
            // state.isForgetPwd = false;
            return
          }
          state.submitLoading = false;
          message.success("修改成功");
          LoginChange("pwd");
          state.isForgetPwd = false;
        })
        .catch(() => {
          state.submitLoading = false;
        });
    };

    const setUserToken = (token) => {
      utils
        .setUserToken(token)
        .then(() => {
          let params = {
            team_name:
              state.loginChangeData?.key == "code" && state.team_name
                ? state.team_name
                : undefined,
          };
          let code =
            localStorage.getItem("INVITE_CODE") ||
            localStorage.getItem("teamInviteCode");
          if (code) {
            params.code = code;
            localStorage.removeItem("INVITE_CODE");
            localStorage.removeItem("teamInviteCode");
          }
          request
            .get("/work_ai", "/user/info", { ...params })
            .then((userResult) => {
              store.commit("SET_TOKEN", userResult.user.user_token);
              store.commit("SET_USER_INFO", userResult.user);
              context.emit("loginCallback");
            });
        })
        .catch(() => {
          state.submitLoading = false;
        });
    };

    // 用户服务条款
    const toUserAgreement = (type, url) => {
      // window.open(`${window.location.origin}#/UseAgreement`);
      if (type == "user_agreement_url") {
        state.agreementTitle = "用户服务条款";
      } else if (type == "privacy_agreement") {
        state.agreementTitle = "隐私协议";
      }
      state.currentAgreeMentUrl = url;
      state.userTextVisible = true;
    };

    const imageVerifyInputRef = ref(null);

    const getVerifyImage = () => {
      request.get("/message", "/verify/image", {}).then((res) => {
        if (res.token && res.image) {
          state.imageVerifyToken = res.token;
          state.imageVerifyImg = res.image;
          state.showImageVerify = true;
          nextTick(() => {
            if (imageVerifyInputRef.value) {
              imageVerifyInputRef.value.focus();
            }
          });
        }
      });
    };

    const closeImageVerify=()=>{
      state.showImageVerify = false
    }

    const LoginChange = (type) => {
      state.password = "";
      state.code = "";
      state.verifyCode = "";
      state.team_name = "";
      state.repeatPassword = "";
      state.isForgetPwd = false;
      if (type == "Verificode") {
        state.loginChangeData = {
          text: "验证码登录",
          key: type,
        };
      } else {
        state.loginChangeData = {
          text: type === "code" ? "验证码登录" : "密码登录",
          key: type,
        };
      }
    };

    const forgotPassword = () => {
      message.warn("请使用验证码登录后在个人中心修改");
    };
    const userTextClose = () => {
      state.userTextVisible = false;
    };
    let qrcodeIcon = new URL(
      utils.staticPath + "images/workAi/shotstack/qrcode-icon.png",
      import.meta.url
    ).href;
    let phoneIcon = new URL(
      utils.staticPath + "images/workAi/shotstack/phone-icon.png",
      import.meta.url
    ).href;
    const btnIcon = computed(() => {
      return state.loginMode == "scan" ? phoneIcon : qrcodeIcon;
    });
    const loginTypeSwitchValue = computed(() => {
      return state.loginMode == "scan" ? "code" : "scan";
    });
    const imgIconStyle = computed(() => {
      return state.loginMode == "scan"
        ? { right: "0px", top: "5px" }
        : { right: "5px", top: "5px" };
      return state.loginMode == "scan"
        ? { right: "5px", top: "0px" }
        : { right: 0, top: 0 };
    });
    const maskStyle = computed(() => {
      return state.loginMode == "scan"
        ? { clipPath: "polygon(0 0, 100% 80%, 100% 100%, 0 100%)" }
        : { clipPath: "polygon(0 0, 100% 100%, 100% 100%, 0 100%)" };
    });
    return {
      ...toRefs(state),
      systemLogo,
      onClose,
      changeLoginMode,
      getCode,
      submitLogin,
      toUserAgreement,
      phoneInputRef,
      getVerifyImage,
      imageVerifyInputRef,
      getSmsCode,
      LoginChange,
      forgotPassword,
      userTextClose,
      handleChangeResetPwd,
      handleChangePassword,
      btnIcon,
      loginTypeSwitchValue,
      imgIconStyle,
      maskStyle,
      onInputChange,
      closeImageVerify
    };
  },
});
</script>

<style lang="less">
.login_modal {
  .ss-modal-content {
    box-shadow: none;
    background: transparent;
  }
}
</style>

<style lang="less" scoped>
.modal-content {
  position: relative;
  padding: 62px 38px 34px;
  position: relative;
  background: #ffffff;
  background-size: 100% 100%;
  border-radius: 8px;

  .login_type {
    width: 100%;
    display: flex;
    justify-content: flex-start;

    >div {
      border: 1px solid #d4d4d5;
      min-width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
      margin-right: 20px;
      cursor: pointer;
      padding: 0 15px;
      transition: 0.3s ease;

      &:hover {
        border: 1px solid var(--ss-primary-color);
        color: var(--ss-primary-color);
      }
    }
  }

  .info {
    margin-top: 30px;
    font-size: 16px;
    color: #999;
  }

  .header-title {
    font-weight: 500;
    font-family: Source Han Sans, Source Han Sans;
    font-weight: 500;
    font-size: 18px;
    color: #333333;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .header-qrdesc {
    font-family: Source Han Sans, Source Han Sans;
    font-weight: 400;
    font-size: 14px;
    color: #666666;
    // text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .header-sub-title {
    margin-top: 5px;
    color: #999;
  }

  .scan-header {
    width: 100%;
  }

  .login-qrcode {
    width: 100%;
    height: 100%;
  }

  .switch-type {
    position: absolute;
    top: 0;
    right: 0;
    width: 80px;
    height: 80px;
    cursor: pointer;
    overflow: hidden;

    .switch-type-img {
      width: 70px;
      height: 70px;
      object-fit: cover;
      position: absolute;
    }

    .switch-type-tip {
      background-color: @primary-color;
      color: #fff;
      border-radius: 4px;
      width: 150px;
      height: 32px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
      top: -45px;
      right: 0;

      &::after {
        content: "";
        position: absolute;
        bottom: -4px;
        right: 15px;
        transform: translateX(-50%) rotate(45deg);
        border: 1px solid @primary-color;
        background: @primary-color;
        width: 7.8px;
        height: 7.8px;
        border-left: 0;
        border-bottom: 0;
      }
    }

    .mask {
      position: absolute;
      z-index: 2;
      top: 0;
      background: #ffffff;
      clip-path: polygon(0 0, 100% 100%, 100% 100%, 0 100%);
    }
  }

  .phone-input-wrap {
    width: 360px;
    height: 55px;
    border: 1px solid #e0e0e6;
    border-radius: 10px;
    margin: 0 auto;
    margin-top: 15px;
    transition: 0.3s ease;

    &:hover {
      border: 1px solid var(--ss-primary-color);
      z-index: 999;
    }
  }

  .code-input-wrap {
    width: 360px;
    height: 55px;
    border: 1px solid #e0e0e6;
    border-radius: 10px;
    margin: 0 auto;
    margin-top: 15px;
    transition: 0.3s ease;

    &:hover {
      border: 1px solid var(--ss-primary-color);
      z-index: 999;
    }
  }

  :deep(.phone-input) {
    height: 100%;
    border-radius: 10px;
  }

  :deep(.code-input) {
    height: 100%;
    border-radius: 10px;
  }
}

#captchaModal {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 99999;
  width: 100%;
  height: 100%;
}

.imageVerify-modal-wrap {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.5);

  .imageVerify-modal {
    width: 444px;
    height: 230px;
    background-color: #fff;
    border-radius: 4px;
    padding: 60px 30px 30px 30px;
    position: relative;

    .imageVerify-modal-close {
      position: absolute;
      top: 0;
      right: 0;
      cursor: pointer;
      font-size: 18px;
      padding: 15px;
    }

    .imageVerify-input-wrap {
      border-bottom: 1px solid #f1f1f1;
      padding-bottom: 10px;

      :deep(.imageVerify-input) {
        flex: 1;
        border: none;
        box-shadow: none;
        border-radius: 0;
      }

      .imageVerify-img {
        width: 117px;
        height: 36px;
        margin-left: 10px;
        border: 2px solid #f1f1f1;
      }

      .imageVerify-img-refresh {
        padding: 0 6px;
        margin-left: 5px;
        font-size: 16px;
        cursor: pointer;
      }
    }

    .imageVerify-btn {
      margin-top: 40px;
      width: 100%;
    }
  }
}

.rich-text-wrapper {
  width: 100%;
  height: 600px;
  overflow-y: auto;
  padding: 20px;

  &::-webkit-scrollbar {
    width: 8px;
    /* 滚动条的宽度 */
    height: 10px;
    /* 滚动条的高度，垂直滚动条可能用得上 */
  }

  &::-webkit-scrollbar-thumb {
    background: #eeeeee;
    /* 滑块的背景颜色 */
    border-radius: 10px;
    /* 滑块的圆角 */
  }
}

.code-safe {
  position: absolute;
  inset: 0;
  background-color: rgba(0, 0, 0, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}

.Verificode_btn {
  width: 360px;
  height: 55px;
  border-radius: 10px;
  margin: 20px 0 15px 0;
  border: none;
  font-size: 20px;
}

:deep(.ant-checkbox + span) {
  padding-right: 0 !important;
}
</style>
